package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.form.PageResponse;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/shopping")
public class OrderController {

    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    OrderQueryService orderQueryService;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    /**
     * 创建订单
     */
    @PostMapping("/order")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) {
        String userInfo = servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        request.setUserId(uid);

        // 设置uniqueKey
        String nextSeq = globalIdGeneratorUtil.getNextSeq("1", 1);
        request.setUniqueKey(nextSeq);
        CreateOrderResponse response = orderCoreService.createOrder(request);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderId());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 查询订单详情
     */
    @GetMapping("order/{id}")
    public ResponseData fetchOrder(@PathVariable String id) {

        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();

        orderDetailRequest.setOrderId(id);

        OrderDetail orderDetail = orderCoreService.searchOrderDetail(orderDetailRequest);

        return new ResponseUtil<>().setData(orderDetail);
    }


    /**
     * 删除订单
     */
    @DeleteMapping("/order/{id}")
    public ResponseData delete(@PathVariable String id) {
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();

        deleteOrderRequest.setOrderId(id);

        DeleteOrderResponse response = orderCoreService.deleteOrder(deleteOrderRequest);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getResult());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 取消订单
     *
     * @param request
     * @return
     */
    @PostMapping("/cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {
        // http://124.71.209.81/shopping/cancelOrder

        // 进行订单的取消
        CancelOrderResponse cancelOrderResponse = orderCoreService.cancelOrder(request);
        if (OrderRetCode.SUCCESS.getCode().equals(cancelOrderResponse.getCode())) {
            return new ResponseUtil().setData(cancelOrderResponse);
        }
        return new ResponseUtil().setErrorMsg(cancelOrderResponse.getMsg());
    }

    /**
     * 显示用户所有的订单
     * http://124.71.209.81/shopping/order?size=5&page=1
     */
    @GetMapping("order")
    public ResponseData showOrders(@RequestParam Map requestMap, HttpServletRequest httpServletRequest) {
        // 获取用户id
        // 拿到当前登录用户的token，保存了uid和username信息
        String userInfo = httpServletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());

        OrderListRequest orderListRequest = new OrderListRequest();
        orderListRequest.setUserId(userId);
        // 默认按照创建时间进行倒序排序
        orderListRequest.setSort("create_time desc");
        orderListRequest.setPage(Integer.parseInt((String) requestMap.get("page")));
        orderListRequest.setSize(Integer.parseInt((String) requestMap.get("size")));

        // 查询当前用户的所有订单，可能查不到
        OrderListResponse orderListResponse = orderQueryService.orderList(orderListRequest);

        PageResponse pageResponse = new PageResponse();
        pageResponse.setData(orderListResponse.getDetailInfoList());
        pageResponse.setTotal(orderListResponse.getTotal());

        if (ShoppingRetCode.SUCCESS.getCode().equals(orderListResponse.getCode())) {
            return new ResponseUtil().setData(pageResponse);
        }
        return new ResponseUtil().setErrorMsg(orderListResponse.getMsg());
    }
}
